package top.magicpotato.sample.store;

import top.magicpotato.sample.pojo.constant.PathConst;
import top.magicpotato.sample.pojo.record.MybatisGenBaseInfo;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class ProjectStore {

    private static final String FILE_NAME = "mgProject";

    /**
     * TODO key目前默认总是default 未来扩展做准备
     */
    private static final Map<String, MybatisGenBaseInfo> store = new HashMap<>();

    public static void add(MybatisGenBaseInfo mybatisGenBaseInfo) {
        store.put("default", mybatisGenBaseInfo);
        store();
    }

    public static MybatisGenBaseInfo get() {
        return store.get("default");
    }

    @SuppressWarnings("unchecked")
    public static void load() {
        Path myDbPath = Paths.get(PathConst.STORE_CONFIG, FILE_NAME);
        File mgDb = myDbPath.toFile();
        if (!mgDb.exists()) {
            return;
        }
        try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(myDbPath))) {
            Map<String, MybatisGenBaseInfo> storeTemp = (Map<String, MybatisGenBaseInfo>) ois.readObject();
            store.putAll(storeTemp);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 数据持久化
     */
    public static void store() {
        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(PathConst.STORE_CONFIG, FILE_NAME)))) {
            oos.writeObject(store);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
